<script setup>
import {ref, reactive} from "vue";
import {useRoute, useRouter} from "vue-router";
import {addGoods, goodsManage, getGoodsDetail, editGoods} from "@/api/product";
import {getStorage} from "@/utils/storage";
import {deepClone} from "@zzcpt/zztool";
import {ElMessage} from "element-plus";
import {Plus, Minus} from "@element-plus/icons-vue";
import Editor from "@/components/Editor/index.vue";
import {useAppStore} from "@/store/app";
// 引入uuid
import {v4 as uuidv4} from "uuid";

const imgUrl = import.meta.env.VITE_BASE_API + "/business_account/business_upload_image";

const appStore = useAppStore();
const route = useRoute();
const router = useRouter();
const urlType = route.params.type;

const categoryList = ref([]);

const baseInfoFormRef = ref();
const baseInfoForm = ref({
  goods_name: "", // 标题
  goods_comment: "", // 商品详情
  goods_sku: "", // 规格
  goods_price_per_sku: "", // 价格
  goods_head_image: [], // 商品主图
  goods_category: "", // 分类
  goods_images: [], // 图片
});
const baseInfoFormRule = reactive({
  goods_name: [{required: true, message: "请输入名称", trigger: "blur"}],
  goods_comment: [{required: true, message: "请输入详情", trigger: "blur"}],
  goods_sku: [{required: true, message: "请输入规格", trigger: "blur"}],
  goods_price_per_sku: [{required: true, message: "请输入价格", trigger: "blur"}],
  goods_head_image: [{required: true, message: "请上传图片", trigger: "blur"}],
  goods_category: [{required: true, message: "请选择分类", trigger: "blur"}],
});

const config = ref({
  title: urlType === "add" ? "新增商品" : "修改商品",
});

getProductInfo();

function getProductInfo() {
  if (urlType !== "add") {
    appStore.startLoading({text: "数据获取中...", background: "rgba(0, 0, 0, 0.3)"});
    getGoodsDetail({goods_id: urlType})
      .then((res) => {
        const data = res.data;
        data.goods_head_image = JSON.parse(data.goods_head_image);
        data.goods_images = JSON.parse(data.goods_images);
        baseInfoForm.value = data;
      }).finally(() => {appStore.closeLoading();})
  }
}

const handleRemove = (uploadFile, uploadFiles) => {
};
const previewImgShow = ref(false);
const dialogImageUrl = ref();
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  previewImgShow.value = true;
};
const handleSuccess = (response, uploadFile) => {
  baseInfoForm.value.goods_head_image = [];
  baseInfoForm.value.goods_head_image.push(uploadFile);
};

getCategoryListFn();

async function getCategoryListFn() {
  // 用的是获取商品分类页面的接口
  const res = await goodsManage();
  const data = deepClone(res.data);
  
  function resetFormat(data) {
    for (let key in data) {
      const item = data[key];
      item.label = item.name;
      item.value = item.category_id;
      if (item.hasOwnProperty("children") && item.children.length > 0) {
        resetFormat(item.children);
      }
    }
  }
  
  resetFormat(data);
  // 将JSON转为数组
  const dataArray = []
  for (let key in data) {
    dataArray.push(data[key])
  }
  categoryList.value = dataArray;
}

// 验证提交表单
const verifyForm = () => {
  return new Promise((resolve, reject) => {
    
    baseInfoFormRef.value.validate((valid, fields) => {
      if (valid) {
        resolve(true);
      } else {
        resolve(false)
      }
    });
  });
};
// 提交信息
const submit = async () => {
  const is = await verifyForm();
  if (!is) return;
  // 这样写用于回填，也方便读取
  const head_image = baseInfoForm.value.goods_head_image.map(item => {
    return {
      id: uuidv4(),
      url: item?.response ? item.response.data : item.url
    };
  })
  const images = baseInfoForm.value.goods_images.map(item => {
    return {
      id: uuidv4(),
      url: item?.response ? item.response.data : item.url
    };
  })
  // 获取分类id
  const goods_category = () => {
    if (Array.isArray(baseInfoForm.value.goods_category)) {
      // 数组获取最后一位
      return baseInfoForm.value.goods_category[baseInfoForm.value.goods_category.length - 1];
    }
    return baseInfoForm.value.goods_category;
  }
  const params = {
    goods_name: baseInfoForm.value.goods_name, // 标题
    goods_comment: baseInfoForm.value.goods_comment, // 商品详情
    goods_sku: baseInfoForm.value.goods_sku, // 规格
    goods_price_per_sku: baseInfoForm.value.goods_price_per_sku, // 价格
    goods_head_image: JSON.stringify(head_image), // 商品主图
    goods_category: goods_category(),
    goods_images: JSON.stringify(images), // 图片
  };
  appStore.startLoading({text: "提交中...", background: "rgba(0, 0, 0, 0.3)"});
  if (urlType !== "add") {
    params.goods_id = baseInfoForm.value.id.toString();
    editGoods(params)
      .then((res) => {
        if (res.code === 200) {
          ElMessage.success("修改商品信息成功");
          appStore.closeLoading();
          setTimeout(() => {
            router.push("/product/index");
          }, 2000);
        }
      }).finally(() => {appStore.closeLoading();})
  } else {
    addGoods(params)
      .then((res) => {
        if (res.code === 200) {
          ElMessage.success("添加商品成功");
          appStore.closeLoading();
          setTimeout(() => {
            router.push("/product/index");
          }, 2000);
        }
      }).finally(() => {appStore.closeLoading();})
  }
};
</script>
<template>
  <div class="container">
    <p class="title">{{ config.title }}</p>
    <div class="box mb-1">
      <p class="title">基础信息</p>
      <div>
        <el-form
          ref="baseInfoFormRef"
          :model="baseInfoForm"
          :rules="baseInfoFormRule"
          label-width="auto"
          status-icon
        >
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="baseInfoForm.goods_name"/>
          </el-form-item>
          <el-form-item label="规格" prop="goods_sku">
            <el-input v-model="baseInfoForm.goods_sku"/>
          </el-form-item>
          <el-form-item label="价格" prop="goods_price_per_sku">
            <el-input v-model="baseInfoForm.goods_price_per_sku"/>
          </el-form-item>
          <el-form-item label="分类" prop="goods_category">
            <el-cascader v-model="baseInfoForm.goods_category" :options="categoryList"/>
          </el-form-item>
          <el-form-item prop="goods_head_image" label="主图" required>
            {{}}
            <el-upload
              v-model:file-list="baseInfoForm.goods_head_image"
              :action="imgUrl"
              :on-success="handleSuccess"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              accept="image/*"
              :limit="2"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item prop="goods_images" label="副图">
            <el-upload
              v-model:file-list="baseInfoForm.goods_images"
              :action="imgUrl"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              accept="image/*"
              :limit="6"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品详情" prop="goods_comment" required>
            {{baseInfoForm.goods_comment}}
            <Editor v-model="baseInfoForm.goods_comment"/>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="box">
      <el-button @click="submit">提交</el-button>
    </div>
    <el-dialog v-model="previewImgShow">
      <el-image style="width: 100%; height: auto" :src="dialogImageUrl" fit="fill"/>
    </el-dialog>
  </div>
</template>
